package io.netty.example.jisong.conversation;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;
import java.util.Date;

/**
 * 对话,使用telnet
 * @author jisong.sun on 2019/1/16.
 */
public class ConversationServer {
    private static final StringDecoder DECODER = new StringDecoder(Charset.forName("UTF-8"));
    private static final StringEncoder ENCODER = new StringEncoder(Charset.forName("UTF-8"));
    public static ChannelHandlerContext c1 = null;
    public static ChannelHandlerContext c2 = null;

    public static void main(String[] args) throws InterruptedException {

        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        b.group(boss,worker)
            .channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                    pipeline.addLast(DECODER);
                    pipeline.addLast(ENCODER);
                    pipeline.addLast(new ConversationServerHandler());
                }
            });

        b.bind(8080).sync().channel().closeFuture().sync();
    }

}

class ConversationServerHandler extends SimpleChannelInboundHandler<String> {

    private ChannelHandlerContext ctx;
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(String.format("channelRegistered # channel id %s%n",ctx.channel().id()));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        if(null == ConversationServer.c1){
            ConversationServer.c1 = ctx;
        }else{
            ConversationServer.c2 = ctx;
        }
        ctx.writeAndFlush(String.format("channelActive # online now: %s%n",new Date()));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        if(ConversationServer.c1.equals(ctx)){
            ConversationServer.c2.writeAndFlush(msg+"\r\n");
        }else{
            ConversationServer.c1.writeAndFlush(msg+"\r\n");
        }
        System.out.printf("channelRead0 : %s%n",msg.toString());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.printf("channelInactive%n");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.printf("channelUnregistered%n");
    }
}
